package com.wxd.init;

import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@HandlesTypes({WebApplicationInitializer.class})
public class MySpringServletContainerInitializer implements ServletContainerInitializer {
    /*
     Servlet 3.0+容器(比如Tomcat7)启动时将自动扫描类路径以查找实现Spring的WebApplicationInitializer接口的所有实现，
     将其放进一个Set集合中，提供给ServletContainerInitializer中onStartup方法的第一个参数。
     所以这里的第一个参数set中就包含MyWebApplicationInitializer
     */
    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        System.out.println("onStartup");
        List<WebApplicationInitializer> initializers = new ArrayList<>();

        if (set != null) {
            // 遍历所有的WebApplicationInitializer的实现类，为每一个实现类创建实例对象，并调用onStartUp方法
            for (Class<?> aClass : set) {
                try {
                    if (!aClass.isInterface() && !Modifier.isAbstract(aClass.getModifiers()) && WebApplicationInitializer.class.isAssignableFrom(aClass)) {
                        initializers.add((WebApplicationInitializer)aClass.newInstance());
                    }
                } catch (Exception e) {
                    throw new ServletException("Failed to instantiate WebApplicationInitializer class", e);
                }
            }
        }

        if (initializers.isEmpty()) {
            servletContext.log("No WebApplicationInitializer types detected on classpath");
            return;
        }

        for (WebApplicationInitializer initializer : initializers) {
            initializer.onStartup(servletContext);
        }
    }
}
